﻿using System;
using System.Collections.Generic;
using System.IO;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static WindowsApplication1.MyDefine;
using Newtonsoft.Json;
using System.Reflection.Emit;

namespace WindowsApplication1
{
    public partial class ClbFaultVal : Form
    {
        Byte CLB_DEV_PC = 0;
        Byte CLB_DEV_ECU = 1;
        Byte CLB_DEV_BMS = 3;

        Byte CLB_OPT_READ = 0;
        Byte CLB_OPT_WRITE = 1;
        byte TimeAll_CLB_OPT = 0;
        IList<FaultJsonResult_class> JsonResultsTemp = new List<FaultJsonResult_class>();

        string ClbJSONFilePath = "";
        public ClbFaultVal()
        {
            InitializeComponent();
        }
        private void ClbFaultVal_Load(object sender, EventArgs e)
        {
            label3.Text = "";
            UpLoaddataGridViewClb();

        }
        void UpLoaddataGridViewClb()
        {
            main_form f1 = (main_form)this.Owner;
            ClbJSONFilePath = f1.FaultClbJSONFilePathStr();
            
            progressBar1.Value = 0;
            if(dataGridViewClb.Rows.Count > 10)
                dataGridViewClb.FirstDisplayedScrollingRowIndex = dataGridViewClb.Rows.Count - 5;

            if (File.Exists(ClbJSONFilePath) == false)
                return ;
            
            JsonResultsTemp = f1.UpLoadFaultClbrCjsonFile(ClbJSONFilePath, 1); 
            dataGridViewClb.Rows.Clear();   
            dataGridViewClb.Rows.Add(JsonResultsTemp.Count);
            for (int i = 0; i < JsonResultsTemp.Count; i++)
            {
                dataGridViewClb.Rows[i].Cells["Column9"].Value = 0;
                dataGridViewClb.Rows[i].Cells[1].Value = JsonResultsTemp[i].SignalNum;
                dataGridViewClb.Rows[i].Cells[2].Value = JsonResultsTemp[i].Name;
                dataGridViewClb.Rows[i].Cells[3].Value = JsonResultsTemp[i].Val;
                dataGridViewClb.Rows[i].Cells[4].Value = JsonResultsTemp[i].Unit;
                dataGridViewClb.Rows[i].Cells[5].Value = JsonResultsTemp[i].Min;
                dataGridViewClb.Rows[i].Cells[6].Value = JsonResultsTemp[i].Max;
                dataGridViewClb.Rows[i].Cells[7].Value = JsonResultsTemp[i].Comment;
                dataGridViewClb.Rows[i].Cells[8].Value = "读取";
                dataGridViewClb.Rows[i].Cells[9].Value = "标定";

            }
            dataGridViewClb.FirstDisplayedScrollingRowIndex = 0;
            
        }/// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            UpLoaddataGridViewClb();
            button1.Enabled = true;
            button7.Enabled = true;
            timer1.Enabled = false;
            setsignalcnt = 0;
        }
        

        UInt16 setsignalcnt = 0;
        /// <summary>
        /// 全选/多选发送 标定/读取
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            main_form f1 = (main_form)this.Owner;
            UInt16 signalnumber, setval, clbsuccess = 0 ;
            JsonResultsTemp = f1.GetErrJsonResults();
            if (setsignalcnt < dataGridViewClb.Rows.Count)
            { 
                signalnumber = Convert.ToUInt16(dataGridViewClb.Rows[setsignalcnt].Cells[1].Value);
                setval = Convert.ToUInt16(dataGridViewClb.Rows[setsignalcnt].Cells[3].Value);
                string strText = f1.Send_ClbComm_pack(CLB_DEV_PC, TimeAll_CLB_OPT, signalnumber, setval);
                f1.my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
                label1.Text = strText + " ;" + dataGridViewClb.Rows[setsignalcnt].Cells[2].Value + " 指令发送完成;";
                setsignalcnt++;
                progressBar1.Value = (setsignalcnt * 100) / dataGridViewClb.Rows.Count;
                if (progressBar1.Value > 99) progressBar1.Value = 99;
            }
            else
            {
                for (int i = 0; i < JsonResultsTemp.Count; i++)
                {
                    if(JsonResultsTemp[i].Operation == "SUCCESS")
                    {
                        dataGridViewClb.Rows[i].Cells[3].Value = JsonResultsTemp[i].Val;
                    }
                    else if(clbsuccess == 0)
                    {
                        signalnumber = Convert.ToUInt16(dataGridViewClb.Rows[i].Cells[1].Value);
                        setval = Convert.ToUInt16(dataGridViewClb.Rows[i].Cells[3].Value);
                        string strText = f1.Send_ClbComm_pack(CLB_DEV_PC, TimeAll_CLB_OPT, signalnumber, setval);
                        f1.my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
                        clbsuccess = 1;
                    }
                }
                if (clbsuccess == 0)
                {
                    setsignalcnt = 0;
                    timer1.Enabled = false;
                    button1.Enabled = true;
                    button7.Enabled = true;
                    progressBar1.Value = 100;
                }
            }
            
            label2.Text = progressBar1.Value.ToString()+"%";
        }
        bool threshold_dir = false;
        bool checkLevel(int RowNumber)
        {
            string t1 = "null", t2 = "null", t3 = "null", label_Text;
            Int16 clbNowLevel1 = -1, clbNowLevel2 = -1, clbNowLevel3 = -1;

            t1 = (string)dataGridViewClb.Rows[RowNumber].Cells[7].Value;
            if (RowNumber - 1 > 0)
            {
                t2 = (string)dataGridViewClb.Rows[RowNumber - 1].Cells[7].Value;
            }
            if (RowNumber + 1 < dataGridViewClb.RowCount)
            {
                t3 = (string)dataGridViewClb.Rows[RowNumber + 1].Cells[7].Value;
            }
            if (t1.Contains("低"))
            {
                threshold_dir = false;
            }
            else
            {
                threshold_dir = true;
            }
            if (t1.Contains("Lv1"))
            {
                 clbNowLevel1 = Convert.ToInt16(dataGridViewClb.Rows[RowNumber].Cells[3].Value);
                if (RowNumber + 1 < dataGridViewClb.RowCount )
                {
                     clbNowLevel2 = Convert.ToInt16(dataGridViewClb.Rows[RowNumber + 1].Cells[3].Value);
                }
                if (RowNumber + 2 < dataGridViewClb.RowCount && t3.Contains("Lv3"))
                {
                     clbNowLevel3 = Convert.ToInt16(dataGridViewClb.Rows[RowNumber + 2].Cells[3].Value);
                }
            }
            if (t1.Contains("Lv2"))
            {
                clbNowLevel1 = Convert.ToInt16(dataGridViewClb.Rows[RowNumber - 1].Cells[3].Value);
                clbNowLevel2 = Convert.ToInt16(dataGridViewClb.Rows[RowNumber].Cells[3].Value);
                if (RowNumber + 1 < dataGridViewClb.RowCount)
                {
                     clbNowLevel3 = Convert.ToInt16(dataGridViewClb.Rows[RowNumber + 1].Cells[3].Value);
                }
            }
            if (t1.Contains("Lv3"))
            {
                if (t3.Contains("Lv1"))
                    clbNowLevel1 = Convert.ToInt16(dataGridViewClb.Rows[RowNumber - 2].Cells[3].Value);

                 clbNowLevel2 = Convert.ToInt16(dataGridViewClb.Rows[RowNumber - 1].Cells[3].Value);
                 clbNowLevel3 = Convert.ToInt16(dataGridViewClb.Rows[RowNumber].Cells[3].Value);
            }
            if (clbNowLevel2 > 0)
            {
                if (threshold_dir == true)
                {//高
                    if ((clbNowLevel1 >= clbNowLevel2 && clbNowLevel1 > 0)|| (clbNowLevel2 >= clbNowLevel3 && clbNowLevel3 > 0))
                    {
                        label_Text = "阈值设置错误,重新设置;\r\n注意:Lv1 < Lv2 < Lv3";
                        MessageBox.Show(label_Text, "设置错误");
                        return false;
                    }
                }
                else
                {//低
                    if ((clbNowLevel1 <= clbNowLevel2 && clbNowLevel1 > 0) || (clbNowLevel2 <= clbNowLevel3 && clbNowLevel3 > 0))
                    {
                        label_Text = "阈值设置错误,重新设置;\r\n注意:Lv3 < Lv2 < Lv1";
                        MessageBox.Show(label_Text, "设置错误");
                        return false;
                    }
                }
            }
            return true;
        }
        private void dataGridViewClb_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (timer1.Enabled == true)
                return;
            int RowNumber = dataGridViewClb.CurrentRow.Index;
            string cellstr = dataGridViewClb.CurrentCell.Value.ToString();

            main_form f1 = (main_form)this.Owner;
            JsonResultsTemp = f1.GetErrJsonResults();

            if (cellstr == "读取")
            {      
                string strText = f1.Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_READ, Convert.ToUInt16(dataGridViewClb.Rows[RowNumber].Cells[1].Value), 0);
                f1.my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
                label1.Text = strText + " ;" + dataGridViewClb.Rows[RowNumber].Cells[2].Value + "  读取指令发送完成;";
                UpLoaddataGridViewClb();
            }
            else if (cellstr == "标定")
            {
                UInt16 clbNowVal = Convert.ToUInt16(dataGridViewClb.Rows[RowNumber].Cells[3].Value);
                UInt16 clbMinVal = Convert.ToUInt16(dataGridViewClb.Rows[RowNumber].Cells[5].Value);
                UInt16 clbMaxVal = Convert.ToUInt16(dataGridViewClb.Rows[RowNumber].Cells[6].Value);
                if (clbNowVal < clbMinVal) clbNowVal = clbMinVal;
                if (clbNowVal > clbMaxVal) clbNowVal = clbMaxVal;
                if (checkLevel(RowNumber) == false)
                {
                    dataGridViewClb.Rows[RowNumber].Cells[3].Value = " ";
                    return;
                }
                string strText = f1.Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_WRITE, Convert.ToUInt16(dataGridViewClb.Rows[RowNumber].Cells[1].Value), clbNowVal);
                f1.my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
                label1.Text = strText + " ;" + dataGridViewClb.Rows[RowNumber].Cells[2].Value + "  标定指令发送完成;"; 
            }
            else
            {
                label1.Text = " ";
            }
            label2.Text = "0 %";
            label3.Text = "";
            progressBar1.Value = 0;
        }
        private void dataGridViewClb_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
           
        }
        /// <summary>
        /// 故障阈值的标定、读取
        /// </summary>
        /// <param name="OptType"></param>
        void ClbWirteOrReadfun(byte OptType)
        {
            main_form f1 = (main_form)this.Owner;
            string strText = "";
            int optcnt = 0;
            for (int i = 0; i < dataGridViewClb.Rows.Count; i++)
            {
                if (Convert.ToBoolean(dataGridViewClb.Rows[i].Cells["Column9"].Value))//判断选择框是否被选中
                {
                    if(OptType == CLB_OPT_WRITE)
                        strText = f1.Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_WRITE, Convert.ToUInt16(dataGridViewClb.Rows[i].Cells[1].Value), Convert.ToUInt16(dataGridViewClb.Rows[i].Cells[3].Value));
                    if (OptType == CLB_OPT_READ)
                        strText = f1.Send_ClbComm_pack(CLB_DEV_PC, CLB_OPT_READ, Convert.ToUInt16(dataGridViewClb.Rows[i].Cells[1].Value), 0);
                    f1.my_push_send((uint)DBC_ID.CLB_CANID, strText, 1);
                    optcnt++; 
                    label1.Text = OptType.ToString() + " ; " + optcnt.ToString() + " ; " + strText;
                }
            }
        }
        /// <summary>
        /// write 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
           
            ClbWirteOrReadfun(CLB_OPT_WRITE);
        }
        /// <summary>
        /// read 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            
            ClbWirteOrReadfun(CLB_OPT_READ);
        }
        /// <summary>
        /// 全选框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                for (int i = 0; i < dataGridViewClb.RowCount; i++)
                    dataGridViewClb.Rows[i].Cells["Column9"].Value = 1;//全选
            }
            else
            {
                 for (int i = 0; i < dataGridViewClb.RowCount; i++)
                    dataGridViewClb.Rows[i].Cells["Column9"].Value = 0;//全不选
            }
        }
        /// <summary>
        /// 导出配置文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveDlg = new SaveFileDialog();
            saveDlg.Filter = "故障阈值配置文件(*.json)|*.json";
            if (saveDlg.ShowDialog() == DialogResult.OK)
            {
                FileStream fs1 = new FileStream(saveDlg.FileName, FileMode.Create, FileAccess.Write);
                fs1.Close();
                string destinationFilePath = @saveDlg.FileName;
                File.Copy(ClbJSONFilePath, destinationFilePath, true);//文件复制,可覆盖同名文件
            }
            
        }
        /// <summary>
        /// 加载配置文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            fd.Filter = "故障阈值配置文件(*.json)|*.json";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                main_form f1 = (main_form)this.Owner;
                textBox56.Text = fd.FileName;
                f1.FaultClbJSONFilePathStr(fd.FileName);
                UpLoaddataGridViewClb();
            }
        }
        /// <summary>
        /// 判断 是否 标定成功 ,判断这一次和上一次的状态
        /// </summary>
        string [] LastOperState = new string[100];
        private void timer2_Tick(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridViewClb.Rows.Count; i++)
            {

                if ((LastOperState[i] == "Writing" || LastOperState[i] == "Reading") && JsonResultsTemp[i].Operation == "Success")
                {
                    label3.Text = JsonResultsTemp[i].Name+" 标定/读取 成功 ";
                }
                LastOperState[i] = JsonResultsTemp[i].Operation;

                if (Convert.ToBoolean(dataGridViewClb.Rows[i].Cells["Column9"].Value))//判断选择框是否被选中
                {
                    button3.Enabled = true;
                    button4.Enabled = true;
                    return;
                }
            }
            button3.Enabled = false;
            button4.Enabled = false;
        }
        
        /// <summary>
        /// 一键设置 all
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            main_form f1 = (main_form)this.Owner;
            for (int i = 0; i < JsonResultsTemp.Count; i++)
            {
                JsonResultsTemp[i].Operation = "NULL";
            }
            f1.SetErrJsonResults(JsonResultsTemp);
            label3.Text = "";
            TimeAll_CLB_OPT = CLB_OPT_WRITE;
            progressBar1.Value = 0;
            button1.Enabled = false;
            button7.Enabled = false;
            timer1.Enabled = true;
        }
        /// <summary>
        /// 一键读取 all
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(object sender, EventArgs e)
        {
            main_form f1 = (main_form)this.Owner;
            for (int i = 0; i < JsonResultsTemp.Count; i++)
            {
                JsonResultsTemp[i].Operation = "NULL";           
            }
            f1.SetErrJsonResults(JsonResultsTemp);
            label3.Text = "";
            progressBar1.Value = 0;
            TimeAll_CLB_OPT = CLB_OPT_READ;
            button1.Enabled = false;
            button7.Enabled = false;
            timer1.Enabled = true;
        }
    }
}
